package com.baoyouqun.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

@Configuration
public class SpringSecurityConfig {


    // 跨域具体配置
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许的来源（生产环境建议指定具体域名，而非*）
        config.setAllowedOrigins(List.of("http://localhost", "http://localhost:8080",  "http://127.0.0.1",  "http://127.0.0.1:8080"));
        // 允许的请求方法（GET、POST等）
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        // 允许的请求头
        config.setAllowedHeaders(List.of("*"));
        // 是否允许携带凭证（如cookie）
        config.setAllowCredentials(true);
        // 跨域请求有效期（秒）
        config.setMaxAge(3600L);

        // 对所有路径生效
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}
